package eu.dominicum.ra.db4o.outbound;

import java.io.Serializable;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ManagedConnectionFactory;

import org.apache.log4j.Logger;

import eu.dominicum.ra.db4o.api.IDb4oConnection;
import eu.dominicum.ra.db4o.api.IDb4oConnectionFactory;

/**
 * This implementation class provides an interface for getting a connection to a
 * Db4o Server. It looks up a ConnectionFactory instance in the JNDI namespace
 * and uses it to get Db4o Server connections.
 */
public class Db4oConnectionFactory implements IDb4oConnectionFactory, Serializable, Referenceable {

	private static final long serialVersionUID = 1L;
	private static Logger LOG = Logger.getLogger(Db4oConnectionFactory.class);

	private ManagedConnectionFactory mcf;
	private ConnectionManager cm;
	private Reference reference;

	public Db4oConnectionFactory() {
	}

	public Db4oConnectionFactory(ManagedConnectionFactory mcf, ConnectionManager cm) {

		LOG.info("Constructing a Db4o Connection Factory");

		this.mcf = mcf;
		if (cm == null) {
			this.cm = new Db4oConnectionManager();
		} else {
			this.cm = cm;
		}
	}

	/**
	 * Gets a connection to the Db4o Server. Passes along Db4o server and user
	 * info.
	 * 
	 * @return Connection Connection instance
	 */
	public IDb4oConnection createConnection() throws ResourceException {

		LOG.info("Creating a Db4o Connection");
		
		IDb4oConnection conn = null;

		conn = (IDb4oConnection) cm.allocateConnection(mcf, null);

		return conn;
	}

	public Reference getReference() throws NamingException {

		return this.reference;
	}
	
	public void setReference(Reference reference) {
		
		this.reference = reference;
	}

}
